<template>
  <div class="user-container animate__animated animate__fadeIn">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
         
        </div>
      </template>

      <el-table
        :data="userList"
        v-loading="loading"
        style="width: 100%"
        border
        stripe
        row-key="userId"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="userId" label="ID" width="80" sortable />
        <el-table-column prop="username" label="用户名" />
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
          sortable
        >
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.state === 1 ? 'success' : 'danger'">
              {{ row.state === 1 ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(row)"
              icon="Edit"
            ></el-button>
            <el-button
              size="small"
              :type="row.state === 1 ? 'danger' : 'success'"
              @click="handleStatusChange(row)"
              :icon="row.state === 1 ? 'Close' : 'Check'"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
        <el-dialog
          v-model="dialogVisible"
          :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
          width="500px"
          :close-on-click-modal="false"
          @close="handleDialogClose"
        >
          <el-form
            ref="formRef"
            :model="userForm"
            :rules="userRules"
            label-width="80px"
            status-icon
          >
        <el-form-item label="用户名" prop="uname">
          <el-input v-model="userForm.uname" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="upass">
          <el-input
            v-model="userForm.upass"
            type="password"
            show-password
            placeholder="请输入密码"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="formLoading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getAllUsers, addUser, updateUser, deleteUser } from "../../api/user";
import "animate.css";
const userList = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const dialogVisible = ref(false);
const dialogType = ref("add");
const formLoading = ref(false);
const formRef = ref(null);
const userForm = ref({
  id: "",
  uname: "",
  upass: "",
});

// 处理对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields();
  userForm.value = {
    id: "",
    uname: "",
    upass: "",
  };
  dialogType.value = "add";
};



const userRules = ref({
  uname: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度应在3-20个字符之间", trigger: "blur" }
  ],
  upass: [
    { 
      required: function() {
        // 仅在添加用户时必填
        return dialogType.value === 'add';
      }, 
      message: "请输入密码", 
      trigger: "blur" 
    },
    { min: 6, max: 20, message: "密码长度应在6-20个字符之间", trigger: "blur" }
  ],
});

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true;
    const res = await getAllUsers();
    userList.value = res.data;
    total.value = res.data.length;
  } catch (error) {
    ElMessage.error(error.message || "获取用户列表失败");
  } finally {
    loading.value = false;
  }
};

// 格式化时间
const formatTime = (time) => {
  return new Date(time).toLocaleString();
};

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchUsers();
};

// 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchUsers();
};

// 排序变化
const handleSortChange = ({ column, prop, order }) => {
  // 这里可以添加排序逻辑
  console.log("排序变化:", prop, order);
};

// 编辑用户
const handleEdit = (row) => {
  dialogType.value = "edit";
  userForm.value = {
    id: row.userId,
    uname: row.username,
    upass: "", // 密码字段为空，如果用户不修改密码则不会更新
  };
  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  try {
    // 表单验证
    await formRef.value.validate();
    formLoading.value = true;
    
    if (dialogType.value === "add") {
      // 添加用户时直接使用表单数据
      await addUser({
        uname: userForm.value.uname,
        upass: userForm.value.upass
      });
      ElMessage({
        type: 'success',
        message: '添加用户成功',
        duration: 2000
      });
    } else {
      // 编辑用户时，构造更新数据对象
      const updateData = {
        id: userForm.value.id,
        uname: userForm.value.uname,
      };
      
      // 只有当密码字段有值时才包含密码
      if (userForm.value.upass.trim()) {
        updateData.upass = userForm.value.upass;
      }
      
      await updateUser(updateData);
      ElMessage({
        type: 'success',
        message: '更新用户成功',
        duration: 2000
      });
    }
    
    // 关闭对话框并刷新用户列表
    dialogVisible.value = false;
    await fetchUsers();
  } catch (error) {
    if (error.name === 'ValidationError') {
      ElMessage({
        type: 'warning',
        message: '请检查表单填写是否正确',
        duration: 3000
      });
    } else {
      console.error("用户操作失败:", error);
      ElMessage({
        type: 'error',
        message: error.message || '操作失败，请重试',
        duration: 3000
      });
    }
  } finally {
    formLoading.value = false;
  }
};

// 修改用户状态
const handleStatusChange = (row) => {
  const action = row.state === 1 ? "禁用" : "启用";
  ElMessageBox.confirm(`确定要${action}用户 ${row.username} 吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteUser(row.userId);
      ElMessage.success(`${action}用户成功`);
      fetchUsers();
    } catch (error) {
      ElMessage.error(error.message || `${action}用户失败`);
    }
  });
};

onMounted(() => {
  fetchUsers();
});
</script>

<style scoped>
.user-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-button + .el-button {
  margin-left: 8px;
}

/* 表格行动画 */
.el-table__row {
  transition: all 0.3s;
}

.el-table__row:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>